<?php
class storeModel extends RPHP_Model
{
    protected $_auth = null;
    //检查权限
    public function checkPriv($pv, $return = true, $menu = true)
    {
        $auth = $this->auth->CheckPriv($pv, $return, $menu);
        if ($return) {
            $this->_auth = $auth;
        }

        return $auth;
    }

    //获取门店信息
    public function getStore($storeid = 0)
    {
        if ($storeid > 0) {
            $where = " AND `store_id`=" . intval($storeid);
        }

        $sql = "SELECT * FROM {$this->_prefix['primary']}store WHERE  `stat`<3 " . $where . " ORDER BY `store_id` ASC";
        if ($storeid > 0) {
            $data = $this->db->getrow($sql);
        } else {
            $data = $this->sql($sql);
        }

        return $data;
    }

    //保存门店
    public function saveStore($da, $storeid = 0)
    {
        $code  = 900;
        $name  = addslashes(htmlspecialchars(trim($da['name'])));
        $codes = addslashes(htmlspecialchars(trim($da['code'])));
        $stat  = intval($da['stat']);
        $type  = intval($da['type']);

        //修改
        if ($storeid > 0) {
            $rs = $this->getStore($storeid);

            if ($rs) {
                $sql = "UPDATE {$this->_prefix['primary']}store SET `name`='" . $name . "',`code`='" . $codes . "',`type`='" . $type . "',`stat`='" . $stat . "',`edit_aid`='" . $this->_auth['aid'] . "',`edit_time`='" . $_SERVER['REQUEST_TIME'] . "' WHERE `store_id` = " . $storeid;

                $rd   = $this->sql($sql);
                $code = 200;

            } else {
                $code = 404;
            }

        }
        //新增
        else {
            if ($name != "") {
                $sql = "INSERT INTO {$this->_prefix['primary']}store
                (`name`,`code`,`type`,`create_time`,`stat`,`create_aid`) VALUES
                ('" . $name . "','" . $codes . "','" . $type . "'," . $_SERVER['REQUEST_TIME'] . "," . $stat . "," . $this->_auth['aid'] . ")";
                $rd = $this->sql($sql);

                if ($rd > 0) {
                    $code = 200;
                } else {
                    $code = 403;
                }

            }
        }
        return $code;

    }
    //库存列表
    public function getStockList($para, $page = 1, $pagesize = 20)
    {

        $where = "GD.`is_delete`=0";

        if ($para) {

            if ($para['caid'] != '') {

                $where .= " AND GD.`caid`=" . $para['caid'];
            }
            if ($para['store_id'] != '') {

                $where .= " AND GAN.`store_id`=" . $para['store_id'];
            }

            if ($para['keyword'] != '') {
                $where .= " AND (GD.`goods_name` LIKE '%" . $para['keyword'] . "%' OR GD.`goods_barcode` LIKE '%" . $para['keyword'] . "%' OR GD.`goods_id`= '" . $para['keyword'] . "')";
                // print_r($where);die;
            }
            if (isset($para['is_on_sale']) && $para['is_on_sale'] >= 0) {
                $where .= " AND `is_on_sale`=" . $para['is_on_sale'];
            }

            if ($para['brand_id'] != '') {
                $where .= " AND `brand_id`=" . $para['brand_id'];
            }
        }
        $sql = "SELECT COUNT(*) AS `cnt` FROM {$this->_prefix['primary']}goods_stock AS GAN INNER JOIN {$this->_prefix['primary']}goods_data AS GD ON GAN.goods_id=GD.goods_id WHERE " . $where;
        $cnt = $this->sql($sql);
        if ($cnt[0]['cnt'] > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "GD.`add_time` DESC,GD.`goods_id` DESC";

            $sql = "SELECT GD.`can_separate`,GD.`goods_id`,GD.`goods_sn`,GD.`goods_name`,GD.`goods_sku`,GD.`pic_docid`,GD.`thumb_docid`,GD.`shopid`,GD.`shop_price`,GD.`purchase_price`,GD.`warn_number`,GD.`is_on_sale`,GD.`is_best`,GD.`is_hot`,GD.`is_new`,GD.`is_promote`,GD.`add_time`,GD.`goods_weight`,GD.`market_price`,GD.`caid`,GD.`brand_id`,GD.`relevance_id`,GD.`warehouse_type`,GAN.`number`,GAN.`store_id` FROM {$this->_prefix['primary']}goods_stock AS GAN INNER JOIN {$this->_prefix['primary']}goods_data AS GD ON GAN.goods_id=GD.goods_id WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
            $rs  = $this->sql($sql);
            foreach ($rs as $k => $v) {
                if ($v['pic_docid'] > 0) {
                    $docid[] = $v['pic_docid'];
                }

                if ($v['thumb_docid'] > 0) {
                    $docid[] = $v['thumb_docid'];
                }

            }

            if ($docid) {
                $docs = $this->getDocs($docid);
            }

        }
        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt[0]['cnt'] / $pagesize),
            'count'   => $cnt[0]['cnt'],
            'data'    => $rs,
            'para'    => $para,
            'docs'    => $docs,
        );

    }

    //库存出库列表
    public function getStoreDecNumber($para, $page = 1, $pagesize = 20)
    {

        $where = "1=1";

        if ($para) {

            if ($para['store_id'] != '') {

                $where .= " AND OI.`store_id`=" . $para['store_id'];
            }

            if ($para['keyword'] != '') {
                $where .= " AND (OG.`goods_name` LIKE '%" . $para['keyword'] . "%' OR OG.`goods_id`='" . $para['keyword'] . "' OR OI.`order_id`= '" . $para['keyword'] . "' OR OI.`order_sn` = '" . $para['keyword'] . "')";
                // print_r($where);die;
            }

            if ($para['start_time']) {

                $where .= " AND OI.`add_time` >=" . $para['start_time'];
                $para['start_time'] = date("Y-m-d H:i", $para['start_time']);
            }

            if ($para['end_time']) {

                $where .= " AND OI.`add_time` <=" . $para['end_time'];
                $para['end_time'] = date("Y-m-d H:i", $para['end_time']);
            }

        }
        $sql = "SELECT COUNT(*) AS `cnt` FROM {$this->_prefix['primary']}order_goods AS OG  INNER JOIN {$this->_prefix['primary']}order_info AS OI ON OI.order_id=OG.order_id WHERE " . $where;
        $cnt = $this->sql($sql);

        if ($cnt[0]['cnt'] > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "OI.`add_time` DESC,OG.`goods_id` DESC";

            $sql = "SELECT OI.`order_id`,OI.`mobile`,OI.`store_id`,OI.`order_sn`,OI.`uid`,OI.`order_status`,OI.`pay_status`,OI.`consignee`,OI.`sell_type`,OI.`pay_fee`,OI.`add_time`,OG.`goods_id`,OG.`goods_sn`,OG.`goods_name`,OG.`goods_barcode`,OG.`goods_number`,OG.`goods_price`,OG.`purchase_price`,OG.`market_price`,OG.`warehouse_type`,OG.`sell_type`,OG.`return_goods_status`,OG.`refund_status`,OG.`shipping_status` FROM {$this->_prefix['primary']}order_goods AS OG INNER JOIN {$this->_prefix['primary']}order_info AS OI ON OI.order_id=OG.order_id WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
            $rs  = $this->sql($sql);
            foreach ($rs as $key => $v) {

                if ($v['uid'] > 0) {
                    $uids[] = $v['uid'];
                }
                if ($v['pay_status'] > 0) {

                    $rs[$key]['pay_status'] = '<span class="label label-success">已付款</span>';
                } else {

                    $rs[$key]['pay_status'] = '<span class="label label-primary">未付款</span>';
                }

                if ($v['shipping_status'] > 0) {

                    $rs[$key]['shipping_status'] = '<span class="label label-primary">已发货</span>';
                } else {

                    $rs[$key]['shipping_status'] = '<span class="label label-default">未发货</span>';
                }

            }

            $users = $this->getMemberInfo($uids);

        }

        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt[0]['cnt'] / $pagesize),
            'count'   => $cnt[0]['cnt'],
            'data'    => $rs,
            'para'    => $para,
            'user'    => $users,

        );

    }
    //获取所有类别
    public function getCategory($caid = 0, $isfucaid = false, $shopid = 0)
    {
        if ($isfucaid) {
            $tsql = " AND `fucaid`=" . intval($caid);
        } elseif ($caid > 0) {
            $tsql = " AND `caid`=" . intval($caid);
        }

        if ($shopid > 0) {
            $tsql = " AND `shopid`=" . intval($shopid);
        }

        $sql = "SELECT * FROM {$this->_prefix['primary']}goods_category WHERE  `stat`=1  " . $tsql . " ORDER BY `fucaid` ASC,`sort` ASC,`stat` ASC,`caid` ASC ";

        if ($caid > 0 && !$isfucaid) {
            $newdata = $this->db->getrow($sql);
        } else {
            $data = $this->sql($sql);
            if ($data) {
                if ($isfucaid) {
                    $newdata = $data;
                } else {
                    foreach ($data as $r) {
                        $newdata[$r['fucaid']][$r['caid']] = $r;
                    }
                }
            }
        }
        return $newdata;
    }

    //获取货源品牌
    public function getBrand($brand_id = 0, $shopid = 0, $type = 0)
    {
        if ($type > 0) {
            $tsql = "`stat`=1";
        } else {

            $tsql = "`stat`!=3";
        }
        if ($brand_id > 0) {
            $tsql .= " AND `brand_id`=" . intval($brand_id);
        }

        if ($shopid > 0) {
            $tsql .= " AND `shopid`=" . intval($shopid);
        }

        $sql = "SELECT * FROM {$this->_prefix['primary']}brand WHERE  " . $tsql . " ORDER BY `name` ASC";
        if ($brand_id > 0) {
            $newdata = $this->db->getrow($sql);
        } else {
            $data = $this->sql($sql);
            if ($data) {
                foreach ($data as $r) {
                    $newdata[$r['brand_id']] = $r;
                }
            }
        }

        return $newdata;
    }

    public function getDocs($docid)
    {
        if (is_array($docid)) {
            $where = " WHERE `docid` IN (" . implode(",", array_unique($docid)) . ")";
        } else {
            $where = " WHERE `docid`=" . intval($docid);
        }

        $sql = "SELECT `docid`,`filename`,`create_time` FROM {$this->_prefix['primary']}documents " . $where;
        $rs  = $this->sql($sql);
        if ($rs) {
            foreach ($rs as $r) {
                $doc[$r['docid']] = $this->c['doc_host'] . date("Ymd", $r['create_time']) . "/" . date("H", $r['create_time']) . "/" . date("i", $r['create_time']) . "/" . $r['filename'];

            }
            return $doc;
        } else {
            return false;
        }

    }
    // 获取商品库存
    public function getGoodsNumber($goods_id, $store_id)
    {
        $goodsid  = intval($goods_id);
        $store_id = intval($store_id);
        if ($goodsid > 0) {
            $sql = "SELECT `number` FROM {$this->_prefix['primary']}goods_stock WHERE `goods_id`=" . $goodsid . " AND `store_id`=" . $store_id;
            return $this->db->getone($sql);

        }
    }

    //增加商品库存
    public function saveGoodsNumber($data, $type = true)
    {

        $code          = 900;
        $store_id      = intval($data['store_id']);
        $goods_id      = intval($data['goods_id']);
        $change_number = intval($data['goods_number']);
        if ($change_number > 0 && $goods_id > 0 && $store_id > 0) {
            $number = 0;
            $this->db->begin();
            $commit = false;
            $code   = 403;
            if ($type) {
                $sql = "SELECT `number` FROM {$this->_prefix['primary']}goods_stock WHERE `goods_id`=" . $goods_id . " AND `store_id`=" . $store_id;
                $arr = $this->db->getrow($sql);
                if ($arr) {

                    $number = $arr['number'];
                    $sql    = "UPDATE {$this->_prefix['primary']}goods_stock SET `number`=`number`+" . $change_number . ",`last_aid`=" . $this->_auth['aid'] . ",`last_edit`=" . date('ymd') . " WHERE `goods_id`=" . $goods_id . " AND `store_id`=" . $store_id;

                } else {

                    $sql = "INSERT INTO {$this->_prefix['primary']}goods_stock (`goods_id`,`store_id`,`number`,`last_aid`,`last_edit`) VALUES (" . $goods_id . "," . $store_id . "," . $change_number . "," . $this->_auth['aid'] . "," . date('ymd') . ")";

                }

            } else {
                $sql = "UPDATE {$this->_prefix['primary']}goods_stock SET `number`=" . $change_number . ",`last_aid`=" . $this->_auth['aid'] . ",`last_edit`=" . date('ymd') . " WHERE `goods_id`=" . $goods_id;

            }
            $res = $this->sql($sql);
            if ($res > 0) {
                // 保存记录
                $sql = "INSERT INTO {$this->_prefix['primary']}goods_stock_log (`goods_id`,`store_id`,`type`,`goods_number`,`change_number`,`create_time`,`aid`) VALUES (" . $goods_id . "," . $store_id . ",1," . $number . "," . $change_number . "," . $_SERVER['REQUEST_TIME'] . "," . $this->_auth['aid'] . ")";

                $rcs = $this->sql($sql);
                if ($rcs > 0) {
                    $commit = true;
                }
            }

            if ($commit) {
                $this->db->commit();
                $code = 200;
            } else {
                $this->db->rollback();
            }

        }

        return $code;

    }

    //保存报损数据
    public function saveGoodsDamaged($da)
    {

        $code = 900;

        $goods_id      = intval($da['goods_id']);
        $store_id      = intval($da['store_id']);
        $change_number = intval($da['goods_number']);
        if ($change_number > 0 && $store_id > 0 && $goods_id > 0) {
            $sql  = "SELECT `number` FROM {$this->_prefix['primary']}goods_stock WHERE `goods_id`=" . $goods_id . " AND `store_id`=" . $store_id;
            $data = $this->db->getrow($sql);

            if ($data) {
                if ($data['number'] >= $change_number) {
                    $this->db->begin();
                    $commit = false;
                    $code   = 403;

                    $sql = "UPDATE {$this->_prefix['primary']}goods_stock SET `number`=`number`-" . $change_number . " WHERE `goods_id`=" . $goods_id . " AND `store_id`=" . $store_id;

                    $res = $this->sql($sql);
                    if ($res > 0) {
                        // 保存记录
                        $sql = "INSERT INTO {$this->_prefix['primary']}goods_stock_log (`goods_id`,`store_id`,`type`,`goods_number`,`change_number`,`create_time`,`aid`,`note`) VALUES (" . $goods_id . "," . $store_id . ",2," . $data['number'] . "," . $change_number . "," . $_SERVER['REQUEST_TIME'] . "," . $this->_auth['aid'] . ",'" . addslashes(htmlspecialchars(trim($da['note']))) . "')";

                        $rcs = $this->sql($sql);
                        if ($rcs > 0) {
                            $commit = true;
                        }
                    }

                    if ($commit) {
                        $this->db->commit();
                        $code = 200;
                    } else {
                        $this->db->rollback();
                    }

                } else {
                    $code = 680;
                }

            } else {
                $code = 404;
            }

        }

        return $code;

    }

    //获取商品ID
    public function getGoodsId($da)
    {
        $arr           = array();
        $arr['code']   = 900;
        $arr['msg']    = "输入商品条码有误";
        $goods_barcode = trim($da['goods_barcode']);
        $store_id      = intval($da['store_id']);
        if ($goods_barcode && $store_id) {
            $sql  = "SELECT `goods_id`,`goods_name`,`shop_price` FROM {$this->_prefix['primary']}goods_data WHERE `goods_barcode`='" . $goods_barcode . "'";
            $data = $this->sql($sql);

            if ($data) {

                $arr['code']  = 200;
                $arr['msg']   = "成功";
                $arr['goods'] = $data;

            }

        } else {

            $arr['code'] = 901;
            $arr['msg']  = "商品条码或者门店不能为空";
        }
        return $arr;
    }

    //获取用户昵称

    public function getMemberInfo($uid)
    {
        if ($uid) {
            $sql  = "SELECT `uid`,`realname`,`headimgurl`,`member_level` FROM {$this->_prefix['primary']}member_account WHERE `uid` IN (" . implode(",", array_unique($uid)) . ")";
            $data = $this->sql($sql);

            if ($data) {
                foreach ($data as $r) {
                    $user[$r['uid']] = $r;
                    /* if ($r['headimgurl'] > 0) {
                $docid[] = $r['headimgurl'];
                } */

                }
//                 if ($docid) {
                //                     $docs = $this->getDocs($docid);
                //                 }

                return $user;
            } else {
                return false;
            }

        }
    }

    //库存列表
    public function getBreakage($para, $page = 1, $pagesize = 20)
    {

        $where = "GD.`is_delete`=0 AND GAN.`type`=2 ";

        if ($para) {

            if ($para['caid'] != '') {
                $where .= " AND GD.`caid`=" . $para['caid'];
            }
            if ($para['store_id'] != '') {
                $where .= " AND GAN.`store_id`=" . $para['store_id'];
            }

            if ($para['keyword'] != '') {
                $where .= " AND (GD.`goods_name` LIKE '%" . $para['keyword'] . "%' OR GD.`goods_barcode` LIKE '%" . $para['keyword'] . "%' OR GD.`goods_id`= '" . $para['keyword'] . "')";
            }
            if ($para['brand_id'] != '') {
                $where .= " AND `brand_id`=" . $para['brand_id'];
            }
        }
        $sql = "SELECT COUNT(*) AS `cnt` FROM {$this->_prefix['primary']}goods_stock_log AS GAN INNER JOIN {$this->_prefix['primary']}goods_data AS GD ON GAN.`goods_id`=GD.`goods_id` WHERE " . $where;
        $cnt = $this->sql($sql);
        if ($cnt[0]['cnt'] > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "GD.`add_time` DESC,GD.`goods_id` DESC";

            $sql = "SELECT GD.*,GAN.* FROM {$this->_prefix['primary']}goods_stock_log AS GAN INNER JOIN {$this->_prefix['primary']}goods_data AS GD ON GAN.`goods_id`=GD.`goods_id` WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
            $rs  = $this->sql($sql);
            foreach ($rs as $k => $v) {
                if ($v['pic_docid'] > 0) {
                    $docid[] = $v['pic_docid'];
                }

                if ($v['thumb_docid'] > 0) {
                    $docid[] = $v['thumb_docid'];
                }
            }
            if ($docid) {
                $docs = $this->getDocs($docid);
            }

        }
        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt[0]['cnt'] / $pagesize),
            'count'   => $cnt[0]['cnt'],
            'data'    => $rs,
            'para'    => $para,
            'docs'    => $docs,
        );

    }
}
